<?php
//获取域名
function baidusu_get_domain() {
	$siteurl = get_bloginfo('url');
	$domain = parse_url($siteurl, PHP_URL_HOST);
	return ltrim($domain, 'www.');
}
//拼接参数
function baidusu_get_parsed_params($param_map) {
	ksort($param_map);
	$param = array();
	foreach($param_map as $key=>$val) {
		array_push($param, $key . '=' . $val);
	}
	$param = implode('&', $param);
	return $param;
}
//公共参数
function baidusu_get_common_params($path, $access_key) {
	$param = array(
		'X-Auth-Access-Key' => $access_key,
		'X-Auth-Nonce' => wp_generate_password(32, false),
		'X-Auth-Path-Info' => $path,
		'X-Auth-Signature-Method' => 'HMAC-SHA1',
		'X-Auth-Timestamp' => time(),
	);

	return $param;
}
//签名
function baidusu_get_signature($str, $secret_key) {
	$sign = hash_hmac('sha1', $str, $secret_key, true);
	$sign = base64_encode($sign);
	return $sign;
}
//获取header
function baidusu_get_header($path, $bizparams) {
	$options = get_option('baidusu');
	$options = unserialize($options);

	$common_params = baidusu_get_common_params($path, $options['access_key']);
	$params = array_merge($common_params, $bizparams);
	$paramsstr = baidusu_get_parsed_params($params);
	$sign = baidusu_get_signature($paramsstr, $options['secret_key']);
	$headers = $common_params;
	$headers['X-Auth-Sign'] = $sign;

	return $headers;
}
//获取Zone ID V31接口需要zone_id
function baidusu_get_zone_id() {
	$path = 'v3/yjs/zones';
	$apiurl = 'https://api.su.baidu.com/' . $path;
	$domain = baidusu_get_domain();
	$params = array(
		'name' => $domain,
	);
	$headers = baidusu_get_header($path, $params);
	$response = wp_remote_get($apiurl, array(
		'timeout' => 10,
		'headers' => $headers,
		'body' => $params,
	));
	if(is_wp_error($response)) return false;
	$response = json_decode($response['body'], true);
	return $response['success'] && isset($response['result']['id']) ? $response['result']['id'] : false;
}

//刷新缓存
function baidusu_refresh_cache($urls='', $type='file') {
	$error = new WP_Error();
	if(!$urls && $type=='file') {
		$error->add('refresh_cache', 'Url不能为空');
		return $error;
	}
	if(!is_array($urls)) {
		$urls = array($urls);
	}
	$urls = array_slice($urls, 0, 500);
	$domain = baidusu_get_domain();
	$path = 'v3/yjs/zones/settings/purge_cache';
	$apiurl = 'https://api.su.baidu.com/' . $path;
	$params = array(
		'domain' => $domain,
		'purge_everything' => 0,
		'files' => join($urls, ';'),
	);
	if($type == 'all') {
		$params['purge_everything'] = 1;
		unset($params['files']);
	}
	$headers = baidusu_get_header($path, $params);
	$request = new WP_Http;
	$response = $request->request($apiurl, array(
		'method' => 'DELETE',
		'timeout' => 30,
		'headers' => $headers,
		'body' => $params,
	));
	if(is_wp_error($response)) return $response;

	$response = json_decode($response['body'], true);
	if(!$response['success']) {
		if(isset($response['errors'][0]['message'])) {
			$error->add('refresh_cache', $response['errors'][0]['message']);
		} else {
			$error->add('refresh_cache', json_encode($response));
		}
		
		return $error;
	}
}
//刷新文章缓存
function baidusu_post_change($post_ID) {
	$url = get_permalink($post_ID);
	baidusu_refresh_cache($url);
}
add_action('post_updated', 'baidusu_post_change', 10, 1); //更新文章时
add_action('deleted_post', 'baidusu_post_change', 10, 1); //删除文章时
add_action('trashed_post', 'baidusu_post_change', 10, 1); //移除文章到回收站
add_action('untrashed_post', 'baidusu_post_change', 10, 1); //从回收站恢复文章
//删除分类缓存
function baidusu_delete_term($term) {
	$url = get_term_link($term);
	baidusu_refresh_cache($url);
}
add_action('delete_term', 'baidusu_delete_term', 10, 1);
//新增文章更新首页、分类页、标签页缓存
function baidusu_insert_post($post_ID, $post, $update) {
	if($update || $post->post_status != 'publish') return;

	$urls = array();
	array_push($urls, home_url('/'));
	array_push($urls, home_url());
	$categories = get_the_category($post_ID);
	if($categories) {
		foreach($categories as $category) {
			$cat_link = get_category_link($category->term_id);
			array_push($urls, $cat_link);
		}
	}
	$tags = get_the_tags($post_ID);
	if($tags) {
		foreach($tags as $tag) {
			$tag_link = get_tag_link($tag->term_id);
			array_push($urls, $tag_link);
		}
	}
	
	baidusu_refresh_cache($urls);
}
add_action('save_post_post', 'baidusu_insert_post', 10, 3);
?>
